package domain

import (
	"bytes"
	"github.com/shirou/gopsutil/net"
	"log"
	"os/exec"
	"strings"
)

/**
网卡流量信息
*/
type Network struct {
	BytesSent   uint64 `json:"bytesSent"`   //发送字节数
	BytesRecv   uint64 `json:"bytesRecv"`   //接收字节数
	PacketsSent uint64 `json:"packetsSent"` //发送数据包
	PacketsRecv uint64 `json:"packetsRecv"` //接收数据包
	Rate        string `json:"rate"`        //速率
}

func (network *Network) NetWorkInfo() error {

	info, err := net.IOCounters(false)
	if err != nil {
		log.Println("获取网卡流量信息失败：", err)
		return err
	}

	log.Println("获取网卡流量信息为：", info)

	//获取网卡的信息
	networkInfo := info[0]
	log.Println("网卡流量信息为：", networkInfo)
	network.BytesSent = networkInfo.BytesSent / 1000 / 1000
	network.BytesRecv = networkInfo.BytesRecv / 1000 / 1000
	network.PacketsSent = networkInfo.PacketsSent / 1000 / 1000
	network.PacketsRecv = networkInfo.PacketsRecv / 1000 / 1000

	//定义变量
	var stdOut, stdErr bytes.Buffer
	//执行shell命令获取网速信息
	cmd := exec.Command("sh", "-c", "dstat -n 1 1 | awk 'END {print}' | awk '{print $2}'")

	cmd.Stdout = &stdOut
	cmd.Stderr = &stdErr

	err = cmd.Run()

	if err != nil {
		log.Println("获取网速失败，失败信息为：", err)
		network.Rate = "0K/s"
	} else {
		content := stdOut.String()
		content = strings.Replace(content, "\n", "", -1)
		network.Rate = content + "/s"
	}

	return nil

}
